package com.entor.util;

import com.entor.entity.User;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private final static String  priKey="123456";


    /**
     * 获取Token
     *
     * @param uid 用户ID
     * @param exp 失效时间，单位分钟
     * @return
     */
    public static String getToken(String uid, int exp) {
        long endTime = System.currentTimeMillis() + 1000 * 60 * exp;
        return Jwts.builder()
                .setSubject(uid)//用户身份
                .claim("user",new User(1,"zhangsan","zhangsan","123456",1,new Date()))
                .setExpiration(new Date(endTime))//过期时间
                .signWith(SignatureAlgorithm.HS512, priKey)//加密
                .compact();
    }
    /**
     * 获取Token
     *
     * @param uid 用户ID
     * @return
     */
    public static String getToken(String uid) {
        long endTime = System.currentTimeMillis() + 1000 * 60 * 1440;
        return Jwts.builder()
                .claim("user",new User(1,"zhangsan","zhangsan","123456",1,new Date()))
                .setSubject(uid)
                .setExpiration(new Date(endTime))
                .signWith(SignatureAlgorithm.HS512, priKey)
                .compact();
    }

    public static Claims getTokenClaim(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(priKey)
                .parseClaimsJws(token)
                .getBody();
        return  claims;
    }

    //获取用户名
    public static String getUsernameByToken(String token){
        return (String) getTokenClaim(token).get("sub");
    }

    /**
     * 检查Token是否合法
     *
     * @param token
     * @return JWTResult
     */
    public static Result checkToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(priKey)
                    .parseClaimsJws(token)
                    .getBody();
            String sub = claims.get("sub", String.class);
            Map<String,Object> map =new HashMap<>();
            map.put("username",sub);
            return Result.success( map);
        } catch (ExpiredJwtException e) {
            // 在解析JWT字符串时，如果‘过期时间字段’已经早于当前时间，将会抛出ExpiredJwtException异常，说明本次请求已经失效
            return Result.error( 301,"token已过期");

        } catch (SignatureException e) {
            // 在解析JWT字符串时，如果密钥不正确，将会解析失败，抛出SignatureException异常，说明该JWT字符串是伪造的
            return Result.error(401, "非法请求");
        } catch (Exception e) {
            return Result.error(401, "非法请求");
        }
    }
    public static class JWTResult {
        private boolean status;
        private String uid;
        private String msg;
        private int code;
        public JWTResult() {
            super();
        }
        public JWTResult(boolean status, String uid, String msg, int code) {
            super();
            this.status = status;
            this.uid = uid;
            this.msg = msg;
            this.code = code;
        }
        public int getCode() {
            return code;
        }
        public void setCode(int code) {
            this.code = code;
        }
        public String getMsg() {
            return msg;
        }
        public void setMsg(String msg) {
            this.msg = msg;
        }
        public boolean isStatus() {
            return status;
        }
        public void setStatus(boolean status) {
            this.status = status;
        }
        public String getUid() {
            return uid;
        }
        public void setUid(String uid) {
            this.uid = uid;
        }

        @Override
        public String toString() {
            return "JWTResult{" +
                    "status=" + status +
                    ", uid='" + uid + '\'' +
                    ", msg='" + msg + '\'' +
                    ", code=" + code +
                    '}';
        }
    }
}
